package com.hc.smsbackup.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.os.Environment;

import com.hc.smsbackup.sms.SMSData;

public class XMLWriter {

	private Document doc;

	public XMLWriter() {

	}

	/**
	 * Write SMS object to XML file
	 */
	public void writeSMSToXml(List<SMSData> smsList) throws Exception {

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

		doc = dBuilder.newDocument();

		// create root Element
		Element rootElement = doc.createElement("SMSBackup");
		

		// create SMS Element
		for (SMSData sms : smsList) {

			rootElement.appendChild(parseSMSObjectToElement(sms));
		}
		doc.appendChild(rootElement);
		
		// write to file
		TransformerFactory transFac = TransformerFactory.newInstance();

		Transformer transformer = transFac.newTransformer();

		DOMSource source = new DOMSource(doc);

		File fXML = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
				"hoai.xml");

		FileOutputStream fileOutPut = new FileOutputStream(fXML);

		Result fileResult = new StreamResult(fileOutPut);

		transformer.transform(source, fileResult);
	}

	/**
	 * Parse SMS Object to XML node
	 * 
	 * @return XML node
	 */
	private Element parseSMSObjectToElement(SMSData sms) {

		Element root = doc.createElement("SMS");

		Element _id = doc.createElement("id");
		_id.appendChild(doc.createTextNode(sms.get_id() == null ? "null" : sms
				.get_id()));
		root.appendChild(_id);

		Element thread_id = doc.createElement("thread_id");
		thread_id
				.appendChild(doc.createTextNode(sms.getThread_id() == null ? "null"
						: sms.getThread_id()));
		root.appendChild(thread_id);

		Element body = doc.createElement("body");
		body.appendChild(doc.createTextNode(sms.getBody() == null ? "null"
				: sms.getBody()));
		root.appendChild(body);

		return root;
	}
}
